<template>
  <div class="admin-product-manage-view" style="margin-top: 50px">
    <a-page-header title="商品管理" />

    <!-- 搜索区域 -->
    <div class="search-container">
      <a-form layout="inline" :model="searchParams">
        <a-form-item label="商品名称">
          <a-input v-model:value="searchParams.name" placeholder="请输入商品名称" allowClear />
        </a-form-item>
        <a-form-item label="商品状态">
          <a-select v-model:value="searchParams.status" style="width: 120px" placeholder="选择状态" allowClear>
            <a-select-option value="1">上架</a-select-option>
            <a-select-option value="0">下架</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="fetchData">查询</a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 表格区域 -->
    <a-card class="table-card">
      <div class="table-operations">
        <a-button type="primary" @click="showAddModal">
          <template #icon><plus-outlined /></template>
          新增商品
        </a-button>
        <a-button @click="fetchData" style="margin-left: 8px">
          <template #icon><reload-outlined /></template>
          刷新
        </a-button>
      </div>

      <a-table
        :dataSource="dataList"
        :columns="columns"
        :loading="loading"
        rowKey="id"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <!-- 价格列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'price'">
            <span class="price">¥{{ record.price?.toFixed(2) }}</span>
          </template>

          <!-- 状态列 -->
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '上架' : '下架' }}
            </a-tag>
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除此商品吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a-button type="primary" danger size="small">
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑商品弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑商品' : '新增商品'"
      :confirmLoading="submitLoading"
      @ok="handleSubmit"
      width="700px"
    >
      <a-form :model="formData" :rules="rules" ref="formRef" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="title" label="商品名称">
              <a-input v-model:value="formData.title" placeholder="请输入商品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="price" label="商品价格">
              <a-input-number v-model:value="formData.price" style="width: 100%" :min="0" :precision="2" placeholder="请输入商品价格" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="category" label="商品分类">
              <a-input v-model:value="formData.category" placeholder="请输入商品分类" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="status" label="商品状态">
              <a-select v-model:value="formData.status" placeholder="请选择商品状态">
                <a-select-option :value="1">上架</a-select-option>
                <a-select-option :value="0">下架</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item name="coverImg" label="商品图片">
          <a-input v-model:value="formData.coverImg" placeholder="请输入图片URL" />
          <div class="image-preview" v-if="formData.coverImg">
            <img :src="formData.coverImg" alt="商品预览图" />
          </div>
        </a-form-item>

        <a-form-item name="specify" label="商品规格">
          <a-input v-model:value="formData.specify" placeholder="请输入商品规格" />
        </a-form-item>

        <a-form-item name="description" label="商品描述">
          <a-textarea v-model:value="formData.description" :rows="4" placeholder="请输入商品描述" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { message } from "ant-design-vue";
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { listProductsVoByPage, updateProducts, deleteProducts } from "@/api/productController";

// 表格列定义
const columns = [
  { title: '商品名称', dataIndex: 'title', key: 'title' },
  { title: '价格', dataIndex: 'price', key: 'price' },
  { title: '分类', dataIndex: 'category', key: 'category' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '操作', key: 'action', width: 150 },
];

// 数据与加载状态
const dataList = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);

// 搜索参数
const searchParams = reactive({
  current: 1,
  pageSize: 10,
  name: '',
  status: undefined,
});

// 分页配置
const pagination = computed(() => ({
  total: total.value,
  current: searchParams.current,
  pageSize: searchParams.pageSize,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
}));

// 表单数据与校验规则
const formRef = ref();
const modalVisible = ref(false);
const submitLoading = ref(false);
const isEdit = ref(false);

const formData = reactive({
  id: undefined,
  title: '',
  price: 0,
  specify: '',
  description: '',
  coverImg: '',
  category: '',
  status: 1,
});

const rules = {
  title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  status: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
};

// 重置搜索条件
const resetSearch = () => {
  searchParams.name = '';
  searchParams.status = undefined;
  fetchData();
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await listProductsVoByPage(searchParams);
    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data.records ?? [];
      total.value = res.data.data.total ?? 0;
    } else {
      message.error('获取数据失败: ' + (res.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('获取数据出错:', error);
    message.error('获取数据出错');
  } finally {
    loading.value = false;
  }
};

// 处理表格分页、排序、筛选变化
const handleTableChange = (pag: any) => {
  searchParams.current = pag.current;
  searchParams.pageSize = pag.pageSize;
  fetchData();
};

// 显示新增商品弹窗
const showAddModal = () => {
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    title: '',
    price: 0,
    specify: '',
    description: '',
    coverImg: '',
    category: '',
    status: 1,
  });

  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

// 编辑商品
const handleEdit = (record: any) => {
  isEdit.value = true;
  // 复制记录数据到表单
  Object.assign(formData, {
    id: record.id,
    title: record.title,
    price: record.price,
    specify: record.specify,
    description: record.description,
    coverImg: record.coverImg,
    category: record.category,
    status: record.status,
  });
  modalVisible.value = true;
};

// 删除商品
const handleDelete = async (record: any) => {
  try {
    const res = await deleteProducts(record.id);
    if (res.data.code === 0 && res.data.data) {
      message.success('删除成功');
      fetchData();
    } else {
      message.error('删除失败: ' + (res.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('删除出错:', error);
    message.error('删除出错');
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate();

    submitLoading.value = true;
    const res = await updateProducts(formData);

    if (res.data.code === 0 && res.data.data) {
      message.success(isEdit.value ? '更新成功' : '添加成功');
      modalVisible.value = false;
      fetchData();
    } else {
      message.error((isEdit.value ? '更新' : '添加') + '失败: ' + (res.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('提交表单出错:', error);
    message.error('表单验证失败或提交出错');
  } finally {
    submitLoading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.admin-product-manage-view {
  padding: 24px;
  width: 100%;
  max-width: 100%;
  margin: 0;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.search-container {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.table-operations {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}

.price {
  color: #f5222d;
  font-weight: 500;
}

.image-preview {
  margin-top: 8px;
  width: 100px;
  height: 100px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 4px;
  overflow: hidden;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

:deep(.ant-table) {
  background-color: #fff;
  border-radius: 4px;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-btn-primary) {
  border-radius: 4px;
}
</style>
